package service.velocity;

import application.WicketApplication;
import dao.inte.TemplateRepository;
import org.apache.commons.collections.ExtendedProperties;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.resource.Resource;
import org.apache.velocity.runtime.resource.loader.ResourceLoader;
import org.apache.wicket.Application;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;


public class CustomVelocityLoader extends ResourceLoader {
    private static Logger logger = Logger.getLogger(CustomVelocityLoader.class.getName());

    TemplateRepository templateRepository;

    @Override
    public void init(ExtendedProperties configuration) {
        templateRepository = (TemplateRepository) ((WicketApplication) Application.get()).getBean("templateRepository");

    }

    @Override
    public InputStream getResourceStream(String source) throws ResourceNotFoundException {
        try {
//            System.err.println(templateRepository);
            if (templateRepository == null) {
                templateRepository = (TemplateRepository) ((WicketApplication) Application.get()).getBean("templateRepository");
            }

            byte currentXMLBytes[] = new byte[0];
            currentXMLBytes = templateRepository.findByKey(source).getValue().getBytes();
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(currentXMLBytes);
            return byteArrayInputStream;
        } catch (Exception e) {
            logger.log(Level.SEVERE, null, e);
            throw new ResourceNotFoundException(e);

        }


    }

    @Override
    public boolean isSourceModified(Resource resource) {
        return true;
    }

    @Override
    public long getLastModified(Resource resource) {
        return 0;
    }

    public void setTemplateRepository(TemplateRepository templateRepository) {
        this.templateRepository = templateRepository;
    }
}
